using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RiceShop.Models;
using RiceShop.Services;
using System.Security.Claims;

namespace RiceShop.Controllers
{
    /// <summary>
    /// Paylinks支付控制器
    /// </summary>
    [ApiController]
    [Route("api/paylinks")]
    [Authorize]
    public class PaylinksController : ControllerBase
    {
        private readonly IPaylinksPaymentService _paymentService;
        private readonly ILogger<PaylinksController> _logger;

        public PaylinksController(
            IPaylinksPaymentService paymentService,
            ILogger<PaylinksController> logger)
        {
            _paymentService = paymentService;
            _logger = logger;
        }

        /// <summary>
        /// 创建小程序支付订单
        /// </summary>
        /// <param name="request">支付请求</param>
        /// <returns>支付信息</returns>
        [HttpPost("mini-program-pay")]
        public async Task<ApiResponse<PaymentInfo>> CreateMiniProgramPayment([FromBody] CreateMiniProgramPaymentRequest request)
        {
            try
            {
                var userId = GetUserId();
                var paymentInfo = await _paymentService.CreateMiniProgramPaymentAsync(request.OrderNo, userId, request.OpenId);
                
                return ApiResponse<PaymentInfo>.Ok(paymentInfo, "支付订单创建成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建小程序支付订单失败");
                return ApiResponse<PaymentInfo>.Error($"创建支付订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建APP支付订单
        /// </summary>
        /// <param name="request">支付请求</param>
        /// <returns>支付信息</returns>
        [HttpPost("app-pay")]
        public async Task<ApiResponse<PaymentInfo>> CreateAppPayment([FromBody] CreateAppPaymentRequest request)
        {
            try
            {
                var userId = GetUserId();
                var paymentInfo = await _paymentService.CreateAppPaymentAsync(request.OrderNo, userId);
                
                return ApiResponse<PaymentInfo>.Ok(paymentInfo, "支付订单创建成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建APP支付订单失败");
                return ApiResponse<PaymentInfo>.Error($"创建支付订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建H5支付订单
        /// </summary>
        /// <param name="request">支付请求</param>
        /// <returns>支付信息</returns>
        [HttpPost("h5-pay")]
        public async Task<ApiResponse<PaymentInfo>> CreateH5Payment([FromBody] CreateH5PaymentRequest request)
        {
            try
            {
                var userId = GetUserId();
                var clientIp = GetClientIp();
                var paymentInfo = await _paymentService.CreateH5PaymentAsync(request.OrderNo, userId, clientIp);
                
                return ApiResponse<PaymentInfo>.Ok(paymentInfo, "支付订单创建成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建H5支付订单失败");
                return ApiResponse<PaymentInfo>.Error($"创建支付订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建支付宝APP支付订单
        /// </summary>
        /// <param name="request">支付请求</param>
        /// <returns>支付信息</returns>
        [HttpPost("alipay-app-pay")]
        public async Task<ApiResponse<PaymentInfo>> CreateAlipayAppPayment([FromBody] CreateAppPaymentRequest request)
        {
            try
            {
                var userId = GetUserId();
                var paymentInfo = await _paymentService.CreateAlipayAppPaymentAsync(request.OrderNo, userId);
                
                return ApiResponse<PaymentInfo>.Ok(paymentInfo, "支付宝APP支付订单创建成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建支付宝APP支付订单失败");
                return ApiResponse<PaymentInfo>.Error($"创建支付宝支付订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建支付宝H5支付订单
        /// </summary>
        /// <param name="request">支付请求</param>
        /// <returns>支付信息</returns>
        [HttpPost("alipay-h5-pay")]
        public async Task<ApiResponse<PaymentInfo>> CreateAlipayH5Payment([FromBody] CreateH5PaymentRequest request)
        {
            try
            {
                var userId = GetUserId();
                var clientIp = GetClientIp();
                var paymentInfo = await _paymentService.CreateAlipayH5PaymentAsync(request.OrderNo, userId, clientIp);
                
                return ApiResponse<PaymentInfo>.Ok(paymentInfo, "支付宝H5支付订单创建成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建支付宝H5支付订单失败");
                return ApiResponse<PaymentInfo>.Error($"创建支付宝支付订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 查询支付状态
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <returns>支付状态</returns>
        [HttpGet("query/{orderNo}")]
        public async Task<ApiResponse<PaymentQueryResult>> QueryPaymentStatus(string orderNo)
        {
            try
            {
                var result = await _paymentService.QueryPaymentStatusAsync(orderNo);
                return ApiResponse<PaymentQueryResult>.Ok(result, "查询成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询支付状态失败");
                return ApiResponse<PaymentQueryResult>.Error($"查询支付状态失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 关闭支付订单
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <returns>操作结果</returns>
        [HttpPost("close/{orderNo}")]
        public async Task<ApiResponse<bool>> ClosePayment(string orderNo)
        {
            try
            {
                var result = await _paymentService.ClosePaymentAsync(orderNo);
                return ApiResponse<bool>.Ok(result, result ? "订单关闭成功" : "订单关闭失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "关闭支付订单失败");
                return ApiResponse<bool>.Error($"关闭支付订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 申请退款
        /// </summary>
        /// <param name="request">退款请求</param>
        /// <returns>退款结果</returns>
        [HttpPost("refund")]
        public async Task<ApiResponse<RefundRecord>> ApplyRefund([FromBody] ApplyRefundRequest request)
        {
            try
            {
                var refundRecord = await _paymentService.ApplyRefundAsync(request.OrderNo, request.RefundAmount, request.RefundReason);
                return ApiResponse<RefundRecord>.Ok(refundRecord, "退款申请成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "申请退款失败");
                return ApiResponse<RefundRecord>.Error($"申请退款失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 查询退款状态
        /// </summary>
        /// <param name="refundNo">退款单号</param>
        /// <returns>退款状态</returns>
        [HttpGet("refund/{refundNo}")]
        public async Task<ApiResponse<RefundRecord?>> QueryRefundStatus(string refundNo)
        {
            try
            {
                var result = await _paymentService.QueryRefundStatusAsync(refundNo);
                return ApiResponse<RefundRecord?>.Ok(result, "查询成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询退款状态失败");
                return ApiResponse<RefundRecord?>.Error($"查询退款状态失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 支付回调通知
        /// </summary>
        /// <returns>回调响应</returns>
        [HttpPost("notify")]
        [AllowAnonymous]
        public async Task<IActionResult> PaymentNotify()
        {
            try
            {
                using var reader = new StreamReader(Request.Body);
                var body = await reader.ReadToEndAsync();
                
                _logger.LogInformation("收到支付回调: {Body}", body);
                
                var result = await _paymentService.HandlePaymentNotifyAsync(body);
                
                if (result)
                {
                    return Ok(new { code = "SUCCESS", message = "OK" });
                }
                else
                {
                    return BadRequest(new { code = "FAIL", message = "处理失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理支付回调失败");
                return BadRequest(new { code = "FAIL", message = "处理失败" });
            }
        }

        /// <summary>
        /// 退款回调通知
        /// </summary>
        /// <returns>回调响应</returns>
        [HttpPost("refund-notify")]
        [AllowAnonymous]
        public async Task<IActionResult> RefundNotify()
        {
            try
            {
                using var reader = new StreamReader(Request.Body);
                var body = await reader.ReadToEndAsync();
                
                _logger.LogInformation("收到退款回调: {Body}", body);
                
                var result = await _paymentService.HandleRefundNotifyAsync(body);
                
                if (result)
                {
                    return Ok(new { code = "SUCCESS", message = "OK" });
                }
                else
                {
                    return BadRequest(new { code = "FAIL", message = "处理失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理退款回调失败");
                return BadRequest(new { code = "FAIL", message = "处理失败" });
            }
        }

        #region 私有方法

        /// <summary>
        /// 获取用户ID
        /// </summary>
        private long GetUserId()
        {
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim != null && long.TryParse(userIdClaim.Value, out var userId))
            {
                return userId;
            }
            throw new UnauthorizedAccessException("用户未登录");
        }

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        private string GetClientIp()
        {
            return Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1";
        }

        #endregion
    }

    #region 请求模型

    /// <summary>
    /// 创建小程序支付请求
    /// </summary>
    public class CreateMiniProgramPaymentRequest
    {
        /// <summary>
        /// 订单号
        /// </summary>
        public string OrderNo { get; set; } = string.Empty;

        /// <summary>
        /// 用户OpenId
        /// </summary>
        public string OpenId { get; set; } = string.Empty;
    }

    /// <summary>
    /// 创建APP支付请求
    /// </summary>
    public class CreateAppPaymentRequest
    {
        /// <summary>
        /// 订单号
        /// </summary>
        public string OrderNo { get; set; } = string.Empty;
    }

    /// <summary>
    /// 创建H5支付请求
    /// </summary>
    public class CreateH5PaymentRequest
    {
        /// <summary>
        /// 订单号
        /// </summary>
        public string OrderNo { get; set; } = string.Empty;
    }

    /// <summary>
    /// 申请退款请求
    /// </summary>
    public class ApplyRefundRequest
    {
        /// <summary>
        /// 订单号
        /// </summary>
        public string OrderNo { get; set; } = string.Empty;

        /// <summary>
        /// 退款金额
        /// </summary>
        public decimal RefundAmount { get; set; }

        /// <summary>
        /// 退款原因
        /// </summary>
        public string RefundReason { get; set; } = string.Empty;
    }

    #endregion
} 